/**
 * IPS js公共文件
 * 包含：
 * 1、启动初始化
 * 2、数据获取接口
 */
// 使用Minify合并js、css
var USE_MINIFY = false;
// 模块枚举常量
MOD_MENU 	= 1;	// 菜单
MOD_HEADER 	= 2;	// 头
MOD_FOOTER 	= 3;	// 尾
MOD_MAP		= 4;	// 地图
MOD_VD		= 5;	// 表单验证
MOD_MABC    = 6;   // mapabc地图

function Ips(){
	this.version = '0.1' ;
	this.appPath = this.getAppPath();
	this.menu     = {};
	this.htmls    = new Array();
	this.userinfo = {};
	
	this.options = {
		apiurl: this.appPath + 'inside.php',
		theme: "default",	// 主题所有目录
		modules: [MOD_MENU, MOD_HEADER, MOD_FOOTER], 	// 默认加载的模块
		remote: true,
		// ips.cn
		mapkey: "ABQIAAAAxrHu5EISPYphVttcHp_FWBS7wQTQeJUu810f3ZSHmg0TLMBKwhRbIXv0Wq8dXKka3JRe164NLlxvIw",
		mabckey:"bbc104d078952ef35d1fdd94879a0d132cc04ac2083577d05f272affdd5520601c2197f5b57146df"
	}
	
	// 主是所在路径
	this.themePath = this.appPath + "themes/default/"; 	
	try {
		this.cache = window['sessionStorage'] || {};
	} catch (e) {
		this.cache = {};
	};
	this.flag = {};		// 存一些标志位

	/**
	 * 数据加载器
	 * @param	module    	模块名，为空默认当前index。
	 * @param	method    	方法名，为空默认当前index。
	 * @param	params    	传给服务器数据，和$.ajax.data规则一样。
	 * @param	callback  	成功时的回调函数，不设置则使用阻塞模式，否则使用异步
	 * @param	remote	  	强制决定是否使用远程模式
	 * @param	cached		是否使用客户端缓存，默认为false
	 * @param	expiration	缓存失效时间，单位秒，默认为0不失效
	 * @return	阻塞模式时返回数据
	 **/
	this.load = function(module, method, params, callback, remote, cached, expiration,beforesend){
		module = module || "index";
		method = method || "index";
		params = params || {};
		callback = callback || false;
		remote = remote || this.options.remote;
		cached = cached || false;
		expiration = expiration || 0;
		beforesend = beforesend || false;
		
		var self = this,
			result = false;
		// 检查缓存
		if (cached) {
			var key = module + '/' + method + '/' + $.param(params);
			result = self.cacheGet(key);
			if (result != null) {
				if (callback) callback(result);
				return result;
			}
		}
		
		var purl = this.appPath + 'data/' + module + '/' + method + '.dat';
		if (remote) {
			purl = this.options.apiurl;
			if (purl.indexOf('?') > -1)
				purl += '&';
			else
				purl += '?';
			purl += 't=json&m=' + module + '&f=' + method;
		}
		$.ajax({
			async: callback ? true : false,
			timeout: 150000,
			type: 'POST',
			url: purl,
			data: params,
			datatype: "json",
			beforeSend :function(XMLHttpRequest){
				if(beforesend) beforesend();
			},
			success: function(json) {
				if (typeof json === "string") {
					if (json.length < 1) {
						self.showError(2, ['json无效，数据为空']);
						return;
					}
					result = eval('(' + json + ')');
				} else {
					result = json;
				}
				
				if (result != null && result.code != 0) {
					self.showError(result.code, [result.message]);
					result = false;
				} else {
					if (callback) callback(result.data);
					// 缓存数据
					if (cached) self.cachePut(key, result.data, expiration);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				try {
					if (callback) callback(null);
					self.showError(2, [textStatus + " " + errorThrown]);
				} catch (e) {
				}
			}
		});
		return result ?  result.data : result;
	}
	
	/**
	 * 存入缓存
	 * @param	key			键
	 * @param	value    	值
	 * @param	params    	超时，不设置或<=0则永不超时，单位：秒
	 */
	this.cachePut = function(key, value, expiration) {
		if (key && value) {
			expiration = expiration || 0;
			var timestamp = Date.parse(new Date()) / 1000;
			var cacheItem = {time: timestamp, expiration: expiration, value: value};
			this.cache[key] = JSON.stringify(cacheItem);
		}
	}
	
	/**
	 * 从缓存取值
	 */
	this.cacheGet = function(key) {
		var item = this.cache[key];
		if (item) {
			item = JSON.parse(item);
			var timestamp = Date.parse(new Date()) / 1000;
			if (item.value && (item.expiration <= 0 || timestamp - item.time < item.expiration) )
				return item.value;
		}
		return null;
	}
	
	/**
	 * 清空缓存
	 */
	this.cacheClear = function() {
		if (window['sessionStorage'])
			this.cache.clear();
	}
	
	/**
	 * 删除指定key的缓存
	 */
	this.cacheRemove = function(key) {
		if (window['sessionStorage'])
			this.cache.removeItem(key);
		else
			delete this.cache[key];
	}	

	/** 跳转到错误提示 */
	this.showError = function(code, messages) {
		if(code == 403)
			setTimeout(this.goUrl,1);		
		else
			this.growl("获取数据失败，请重试或联系管理员！");
		// 开启firebug时输出错误描述
		if (typeof(console) != 'undefined')
			for (i = 0; i < messages.length; i++)
				console.debug(messages[i]);
	}
	
	this.goUrl = function () {
		$ips.locate('login','index');
	}
	
	/** 设置是否使用远程数据 */
	this.setRemote = function(remote) {
		this.options.remote = remote;
	}

	/** 启动初始化 **/
	this.startup = function(opts) {
		$.extend(this.options, opts);
		var curModule = this.curModel();
		var key = "index_getconfig_" + curModule;
		// 先取缓存
		var result = this.cacheGet(key);
		if (!result || result == null) {
			var extparams = {'model': curModule};
			result = this.load('index', 'getconfig', extparams);
		}
		if (result.initjs) {
			this.include(result.initjs);
			if (result.userinfo) {
				this.userinfo = result.userinfo;
				// 得到用户信息，缓存
				if (result.userinfo.uid)
					this.cachePut(key, result);
			}
		}
		if (result.theme) {
			this.options.theme = result.theme;
			this.themePath = this.appPath + "themes/" + result.theme + "/";
		}
	}
	
	/** 动态加载一个或一组js/css文件 */
	this.flag.included = {};
	this.include = function(urls) {
		var cache = this.flag.included;
		var extension = extension || false;
		if (typeof urls === "string")
			urls = [urls];
		
		var jsfile = new Array();
		for (i = 0; i < urls.length; i ++) {
			var url = urls[i];
			if (typeof url !== "string") continue;			
			
			// 防止重复加载
			if(cache[url]) continue;
			cache[url] = true;
			
			var extension = url.split('.')[url.split('.').length-1];		
			if(extension == 'css')
				document.write('<link type="text/css" rel="stylesheet" href="' + url + '" />');
			if(extension == 'html')
				this.htmls.push(this.get(url));
			else if(extension == 'js')
				jsfile.push(url);
			else
				document.write('<script src="' + url + '"></script>');
		}
		if (this.options.remote && USE_MINIFY) {
			var str = '';
			for (i = 0; i < jsfile.length; i ++) {
				if (i > 0) str += ',';
				var url = jsfile[i];
				str += url.replace(this.appPath, '/');
			}
			document.write('<script src="/min/?f=' + str + '"></script>');
		} else {
			for (i = 0; i < jsfile.length; i ++)
				document.write('<script src="' + jsfile[i] + '"></script>');
		}
	}
	
	/** 阻塞方式加载页面 */
	this.get = function(url) {
		return $.ajax({url: url, async: false}).responseText;
	}
	
	/** 初始化地图，需要使用地图的页面手动调用 */
	this.initMap = function() {
		$ips.include("http://ditu.google.cn/maps?hl=zh-CN&amp;file=api&amp;v=2&amp;sensor=true&amp;key=" + this.options.mapkey);
	}
	
	/**
	 * 加载模块
	 * @param modules 不设置则加载options中的默认设置
	 * @param usedef  同时载入缺省的模块
	 */
	this.flag.module = {};
	this.loadModules = function(modules, usedef) {
		modules = modules || this.options.modules;
		usedef = usedef || false;
		if (typeof modules === "number")
			modules = [modules];
		if (usedef)
			modules = modules.concat(this.options.modules);
	
		var cache = this.flag.module;
		var files = new Array();
		for (i = 0; i < modules.length; i ++) {
			var module = modules[i];
			
			// 防止重复加载
			if(cache[module]) continue;
			cache[module] = true;
			
			switch (module) {
			case MOD_MENU:		// 菜单
				files.push(this.appPath + "js/jquery.mb.menu/inc/jquery.metadata.js");
				files.push(this.appPath + "js/jquery.mb.menu/inc/jquery.hoverIntent.js");
				files.push(this.appPath + "js/jquery.mb.menu/inc/mbMenu.js");				
				
//				files.push(this.appPath + "css/lib/mainMenu/menu.js");				
				files.push(this.appPath + "themes/default/js/menu_new.js");
				break;
			case MOD_HEADER:	// 头
				var key = "common_header";
				var html = null;//this.cacheGet(key);
				if (html == null) {
					html = this.get(this.themePath + "common/header.html");
					this.cachePut(key, html);
				}
				this.htmls.push(html);
				break;
			case MOD_FOOTER:	// 尾
				var key = "common_footer";
				var html = null;//this.cacheGet(key);
				if (html == null) {
					html = this.get(this.themePath + "common/footer.html");
					html = ['footer', html];
					this.cachePut(key, html);
				}
				this.htmls.push(html);
				break;
			case MOD_MAP:		// 地图
				files.push("http://ditu.google.cn/maps?hl=zh-CN&amp;file=api&amp;v=2&amp;sensor=true&amp;key=" + this.options.mapkey);
				break;
			case MOD_MABC:		// mapabc地图
				files.push("http://app.mapabc.com/apis?&t=flashmap&v=2.4&key=" + this.options.mabckey);
				break;
			case MOD_VD:		// 表单验证
				files.push(this.appPath + "js/validate/jquery.validate.min.js");
				files.push(this.appPath + "js/validate/jquery.validate.ext.js");
				files.push(this.appPath + "js/validate/messages_cn.js");
				break;
			}
		}
		$ips.include(files);
	}
	
	/**
	 * 弹出消息
	 */
	this.growl = function(message) {
		var g = $('#one_jgrowl');
		if (g.length == 0)
			g = $('<div id="one_jgrowl" class="jGrowl bottom-right"></div>').appendTo('body');
		g.jGrowl(message);
	}
}

Ips.prototype  = {
	/**
	 * 返回APP所在的根路径, 用于加载资源文件
	 */
	getAppPath: function(){
		var script = document.getElementsByTagName("script");
		for (var i = 0; i < script.length; i++) {
			var match = script[i].src.match(/ips\.public\.js($|\?.*)/);
			if (match) {
				return script[i].src.replace(/js\/ips\.public\.js.*/, '');
			}
		}
	},
    /**
	 * 解析URL返回GET参数,可以手动传入如:aa=bb&cc=dd
	 **/
    getUrlParams: function(purl) {
        var url = purl || window.location.href;
        var paraObj = {};
        if(url.indexOf("?")<0){
        	return paraObj;
        }
        var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
        for (i=0; j=paraString[i]; i++){
            paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
        }
        return paraObj;
    },
    /**
	 * 填充表单,匹配字段名字结尾的所有值
	 * {name:'xiaoming'} 匹配:name,old_name
	 * 
     * @param	formid    表单ID,不能为空
     * @param   params    JSON格式,如: {name:'xiaoming',age:20} 也可传String,如:aa=bb&cc=dd
     * $param   pre       前缀
	 **/
    fillFormInput: function(formid,params,pre) {
        if(!formid || !params) return;
        pre = pre || '';
        if(typeof(params)=='string') {
            params = this.getUrlParams(params);
        }
        $.each(params,function(k,v) {
            if($('#'+formid+' input[name$='+k+']').length)
                $('#'+formid+' input[name$='+k+']').val(v);
            else if($('#'+pre+k).length)
                $('#'+pre+k).val(v);
        });
    },
	/**
	 * 跳转另一个模块的页面
	 **/
	locate: function(module, method, params) {
		module = module || "index";
		method = method || "index";
		params = params || false;
		var url = this.appPath;
		if (module != "index") url += module + "/";
		url += method + ".html"
		if (params) url += "?" + params;
		window.location = url;
	},
	//当前模块
	curModel:function() {
		var path     = window.location.pathname;
		var ps       = path.split('/');	
		if (ps.length < 3) return "index";
		else return ps[1];
	},
	//当前方法
	curMethod:function() {
		var path = window.location.pathname;
		var ps   = path.split('/');
		if (ps.length < 3) ps = ps[1];
		else ps = ps[2];
		var fs = ps.split('.');
		return fs[0];
	},
	
	/**
	 * 信息提示
	 */
	alert: function(message, callback, width, height, title) {
		title = title || '信息提示';
		ymPrompt.alert(message, width, height, title, callback);
	},

	/**
	 * 成功信息提示
	 */
	succeed: function(message, callback, width, height, title) {
		title = title || '操作成功';
		ymPrompt.succeedInfo(message, width, height, title, callback);
	},

	/**
	 * 保存成功的信息提示
	 */
	saved: function(message, callback, width, height, title, btn) {
		message = message || '保存数据成功！';
		title = title || '操作成功';
		btn = btn || [['返回列表','list'],　['继续添加','add']];
		ymPrompt.succeedInfo({message: message, width: width, height: height, title: title, handler: callback, btn: btn});
	},

	/**
	 * 失败信息提示
	 */
	error: function(message, callback, width, height, title) {
		title = title || '操作失败';
		ymPrompt.errorInfo(message, width, height, title, callback);
	},

	/**
	 * 询问信息
	 */
	confirm: function(message, callback, width, height) {
		ymPrompt.confirmInfo(message, width, height,'信息提示', callback)
	},

	/**
	 * 弹出窗
	 * @param	message	文本/iframe模式的URL
	 * @param	width	宽
	 * @param	height	高
	 * @param	title	标题
	 * @param	callback	回调
	 * @param	iframe		为空则为普通模式，否则填iframe的属性，示例：{id: 'iframe01'}
	 * @param	btn			自定义按钮，示例:[['是','yes'],['否','no'],['取消','cancel']]})
	 **/
	win: function(message, width, height, title, callback, iframe, btn, showmask) {
		ymPrompt.win({message: message, width: width, height: height, title: title, handler: callback, iframe: iframe, btn: btn, showMask: showmask});
		return ymPrompt;
	},
	
	/**
	 * 地址解析
	 * @param	q			地址解析的地址，可经纬度字符串（格式：纬度,经度）
	 * @param	callback	回调函数
	 */
	geo: function(q, callback) {
		callback = callback || false;
		var result = {code: -1};
		var url = "http://ditu.google.cn/maps/geo?hl=zh-CN&q="+q+"&output=json&key=" + this.options.mapkey + "&callback=?";
		$.ajax({
			type: "GET",
			timeout: 5000,
			url: url,
			data: null,
			dataType: "json",
			success: function(p) {
				if(p.Status.code==200) {
					result.code = 0;
					result.total = p.Placemark.length;
					result.poilist = new Array();
					if(result.total > 0){
						var name = p.name; 
						for (var i = 0; i < result.total; i++) {
							var place = p.Placemark[i];
							var point = {};
							point.name = name;
							point.address = place.address.substring(2);
							point.lat = place.Point.coordinates[0];
							point.lng = place.Point.coordinates[1];
							
							// 省、市、县
							var c = place.AddressDetails.Country;
							if (c && c.AdministrativeArea) {
								var prov = c.AdministrativeArea;
								point.province = prov.AdministrativeAreaName;
								if (prov.Locality) {
									point.city = prov.Locality.LocalityName;
									if (prov.Locality.DependentLocality)
										point.county = prov.Locality.DependentLocality.DependentLocalityName;
								}
							}
							result.poilist.push(point);
						}	
					}
				} else {
					result.code = p.Status.code;
				}
				if (callback) callback(result);
			},
			error: function() {
				result.code = 1;
				if (callback) callback(result);
			}
		});
	},
	setGridHight:function() {
		//高度自适应
		$(window).resize(function(){
			var gHeight = $(window).height();	
			var hh = eval(gHeight-270);	
			if(hh<200)
				hh=200;
			$(".bDiv").css("height",hh+"px");
		});
	}
}
var $ips = new Ips();

//运行启动初始化
var opts = {};
//opts.apiurl = 'http://ips.cn/inside.php?XDEBUG_SESSION_START=ECLIPSE_DBGP&KEY=12900567673271&callback=?';

if (opts.remote === false || !USE_MINIFY) {
	document.write('<link type="text/css" rel="stylesheet" href="' + $ips.appPath + 'js/blackbirdjs/blackbird.css" />');
	document.write('<link type="text/css" rel="stylesheet" href="' + $ips.appPath + 'js/ymPrompt/skin/ips/ymPrompt.css" />');
	document.write('<link type="text/css" rel="stylesheet" href="' + $ips.appPath + 'js/jgrowl/jquery.jgrowl.css" />');
	document.write('<link type="text/css" rel="stylesheet" href="' + $ips.appPath + 'js/jquery.mb.menu/css/menu_ips.css" media="screen"/>');
//	document.write('<script src="/js/ips.all.js"></script>');
	
	/**/
	// 加载其它的js和css
	$ips.include([
		$ips.appPath + 'js/ui/jquery.ui.widget.js',
		$ips.appPath + 'js/common.js',
		$ips.appPath + 'js/json2.min.js',
		$ips.appPath + 'js/jquery.metadata.js',
		$ips.appPath + 'js/jquery.sprintf.js',
//		$ips.appPath + 'js/ui/jquery.ui.widget.js',
		$ips.appPath + 'js/jtemplates/jquery-jtemplates.js',
	
		// JS调试工具，在浏览器按F2查看
		$ips.appPath + 'js/blackbirdjs/blackbird.js',
		
		// flexigrid
		$ips.appPath + 'js/flexigrid/jquery.flexigrid.js',
		
		// 弹出窗
		$ips.appPath + 'js/ymPrompt/ymPrompt.js',
		
		// 提示
		$ips.appPath + 'js/jgrowl/jquery.jgrowl_minimized.js',
	
		// 搜索面板
		$ips.appPath + 'css/lib/jkmenu/jkmegamenu.js',
		
		// 自动完成
		$ips.appPath + 'js/acbox/js/jquery.ajaxComboBox.3.5.7.js',
		
		// Tree
//		$ips.appPath + 'js/plugin/jquery.tree.js'
	]);
} else {
	document.write('<link type="text/css" rel="stylesheet" href="/min/?g=css" />');
	document.write('<script src="/min/?g=js"></script>');
}	

// My97DatePicker，用min加载有问题
document.write('<script src="' + $ips.appPath + 'js/My97DatePicker/WdatePicker.js"></script>');

var host = window.location.host;
if (host == 'ips.9.com') {
	opts.mapkey = "ABQIAAAAxrHu5EISPYphVttcHp_FWBSfPudfG5OFYjTaxJ5t6VGk2NPvhRTyVeFPAQ9DCiNsQh-dLG1454Wb7A";
	opts.mabckey = "9f3ee75f1b93856234dac49e6de951a4d8d3ef85b02b18002ed7e596c6b3c7284d2d7df093301c1d";
} else if (host == 'ipstest.huoyunren.com' || host =='ipstest.huoyunren.com:8081') {
//	opts.mapkey = "ABQIAAAAxrHu5EISPYphVttcHp_FWBTRI6LePoIIdamECkL0ct5Nq6jx5RRPeXaKEBX4aciVG86nhlDlqimeWA";
	// 8081
	opts.mapkey = "ABQIAAAAxrHu5EISPYphVttcHp_FWBRLxqsOkMOb4pnn565xqEL-30H23RQHmxSIEhAS586KIXHd5yYwogzRrw";
	opts.mabckey = "4bc6ab0e90c39be299e7e7ae71a842fedf41f6ddd434b92bfcf3d832c6db94a16644742a7e6ae3cd";
} else if (host.indexOf('huoyunren.com') > -1) {
//	opts.mapkey = "ABQIAAAAxT6j61Dz1Mr_n1ES5nEL9hTqHUJVLUcA2hrl2f19JJcStONFhxQCNTN9xJOg-nKVL5_vI4NH4kiPwQ";
	// huoyunren.com
	opts.mapkey = "ABQIAAAAxrHu5EISPYphVttcHp_FWBQJs_GPdA1vC8REkcFwpH2QCEo8thTTbWFw5R4reS3PJzid13GzFOIWDg";
	opts.mabckey = "09b3f18f740d6f0bc44491c170a47d90084a3cb6a956897995fd0664f0d85a5c377b627c7451b0bd";
}
//opts.remote = false;
$ips.startup(opts);

if ($ips.options.remote)
	$ips.include([$ips.appPath + 'themes/default/js/action.js']);

$(function(){ 
	var htmls = $ips.htmls;
	for (i = 0; i < htmls.length; i ++) {
		if( typeof htmls[i]  === 'string' )
			$('body').append(htmls[i]);
		else {
			$('#' + htmls[i][0]).html(htmls[i][1]);
		}
	}
	
});

// 屏蔽所有javascript错误
window.onerror = function() {
};